import React, { useState } from 'react';
import { Form, Input, Select, Button, message, Card, Upload, Progress } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { datasetService } from '../services';

const { Option } = Select;

const DatasetCreate = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState({});
  const navigate = useNavigate();

  // 处理文件上传请求
  const customRequest = async ({ onSuccess, onError, file }) => {
    // 为当前文件初始化进度状态
    setUploadProgress(prev => ({ ...prev, [file.uid]: 0 }));
    
    try {
      // 创建FormData对象
      const formData = new FormData();
      formData.append('file', file);
      
      // 使用datasetService上传文件，传入进度回调
      await datasetService.uploadFile(formData, (progress) => {
        // 更新上传进度
        setUploadProgress(prev => ({ ...prev, [file.uid]: progress }));
      });
      
      // 成功回调
      onSuccess({
        status: 'done',
        response: { url: `file://uploaded/${file.name}` }
      });
    } catch (error) {
      console.error('文件上传失败:', error);
      onError(error);
      message.error(`文件上传失败: ${error.message}`);
    } finally {
      // 上传完成后清除进度状态
      setTimeout(() => {
        setUploadProgress(prev => {
          const newProgress = { ...prev };
          delete newProgress[file.uid];
          return newProgress;
        });
      }, 500);
    }
    
    // 返回一个对象，包含abort方法（可选）
    return {
      abort: () => {
        console.log('取消上传');
        onError(new Error('上传已取消'));
      }
    };
  };



  const handleSubmit = async (values) => {
    setLoading(true);
    try {
      let submitData = {
        name: values.name,
        description: values.description,
        sourceType: values.sourceType,
        fileConfig: values.fileConfig,
        filePattern: values.filePattern
      };

      // 根据数据源类型添加相应的字段
      if (values.sourceType === 'upload') {
        // 对于上传文件类型，处理上传的文件信息
        submitData.fileInfo = values.uploadedFile.map(file => ({
          name: file.name,
          size: file.size,
          type: file.type,
          uploadTime: new Date().toISOString(),
          url: file.response?.url || `file://uploaded/${file.name}`
        }));
      } else {
        // 对于其他类型，添加路径信息
        submitData.sourcePath = values.sourcePath;
        if (values.sourceType === 's3') {
          submitData.s3Credentials = values.s3Credentials;
        }
      }

      console.log('提交的数据:', submitData);
      
      // 使用datasetService创建数据集
      await datasetService.createDataset(submitData);
      
      message.success('数据集创建成功！');
      setLoading(false);
      navigate('/');
    } catch (error) {
      console.error('创建数据集失败:', error);
      message.error('创建数据集失败，请稍后重试');
      setLoading(false);
    }
  };

  const handleCancel = () => {
    navigate('/');
  };

  const onFinishFailed = (errorInfo) => {
    console.log('表单验证失败:', errorInfo);
  };

  return (
    <div>
      <h2>创建数据集</h2>
      <Card style={{ marginTop: 20 }}>
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            sourceType: 'local',
          }}
          onFinish={handleSubmit}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            name="name"
            label="数据集名称"
            rules={[{ required: true, message: '请输入数据集名称' }]}
          >
            <Input placeholder="请输入数据集名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="数据集描述"
            rules={[{ required: false }]}
          >
            <Input.TextArea rows={3} placeholder="请输入数据集描述（可选）" />
          </Form.Item>

          <div style={{ borderTop: '1px solid #f0f0f0', paddingTop: 20, marginTop: 20 }}>
            <h3 style={{ marginBottom: 20 }}>数据源配置</h3>
            
            <Form.Item
              name="sourceType"
              label="数据源类型"
              rules={[{ required: true, message: '请选择数据源类型' }]}
            >
              <Select placeholder="请选择数据源类型">
                <Option value="local">本地文件</Option>
                <Option value="s3">Amazon S3</Option>
                <Option value="upload">上传文件</Option>
              </Select>
            </Form.Item>

            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.sourceType !== currentValues.sourceType}
            >
              {({ getFieldValue }) => {
                const sourceType = getFieldValue('sourceType');
                return sourceType !== 'upload' ? (
                  <Form.Item
                    name="sourcePath"
                    label="数据源路径"
                    rules={[{ required: true, message: '请输入数据源路径' }]}
                  >
                    <Input placeholder="例如: /data/source 或 s3://bucket-name/path" />
                  </Form.Item>
                ) : (
                  <Form.Item
                    name="uploadedFile"
                    label="上传文件"
                    rules={[{ required: true, message: '请上传文件' }]}
                  >
                    <div>
                      <Upload.Dragger 
                        name="file" 
                        customRequest={customRequest}
                        multiple
                        beforeUpload={(file) => {
                          // 文件类型检查
                          const validTypes = ['text/csv', 'application/json', 'application/xml', 'text/plain'];
                          // 检查文件扩展名作为类型检查的补充
                          const validExtensions = ['csv', 'json', 'xml', 'txt'];
                          const fileExt = file.name.split('.').pop().toLowerCase();
                          
                          if (!validTypes.includes(file.type) && !validExtensions.includes(fileExt)) {
                            message.error(`${file.name} 不是支持的文件类型`);
                            return Upload.LIST_IGNORE;
                          }
                          // 文件大小检查（100MB）
                          const isLt100M = file.size / 1024 / 1024 < 100;
                          if (!isLt100M) {
                            message.error(`${file.name} 文件大小不能超过100MB`);
                            return Upload.LIST_IGNORE;
                          }
                          return true;
                        }}
                      >
                        <p className="ant-upload-drag-icon">
                          <UploadOutlined />
                        </p>
                        <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
                        <p className="ant-upload-hint">
                          支持单个或批量上传，建议文件大小不超过100MB<br />
                          支持的文件类型: CSV, JSON, XML, TXT
                        </p>
                      </Upload.Dragger>
                       
                      {/* 上传进度显示 */}
                      {Object.keys(uploadProgress).map(fileUid => (
                        <div key={fileUid} style={{ marginTop: 10 }}>
                          <Progress 
                            percent={uploadProgress[fileUid]} 
                            status="active" 
                            strokeColor={{'0%': '#108ee9', '100%': '#87d068'}}
                          />
                          <p style={{ textAlign: 'center', marginTop: 5, fontSize: 12, color: '#666' }}>
                            正在上传: {uploadProgress[fileUid]}%
                          </p>
                        </div>
                      ))}
                    </div>
                  </Form.Item>
                );
              }}
            </Form.Item>

            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.sourceType !== currentValues.sourceType}
            >
              {({ getFieldValue }) => {
                return getFieldValue('sourceType') === 's3' ? (
                  <Form.Item
                    name="s3Credentials"
                    label="S3 访问凭证"
                    rules={[{ required: true, message: '请输入S3访问凭证' }]}
                  >
                    <Card title="S3 访问凭证">
                      <Form.Item
                        name={['s3Credentials', 'accessKey']}
                        rules={[{ required: true, message: '请输入Access Key' }]}
                      >
                        <Input placeholder="Access Key" />
                      </Form.Item>
                      <Form.Item
                        name={['s3Credentials', 'secretKey']}
                        rules={[{ required: true, message: '请输入Secret Key' }]}
                      >
                        <Input.Password placeholder="Secret Key" />
                      </Form.Item>
                      <Form.Item
                        name={['s3Credentials', 'region']}
                        rules={[{ required: true, message: '请输入区域' }]}
                      >
                        <Input placeholder="Region (例如: us-west-1)" />
                      </Form.Item>
                    </Card>
                  </Form.Item>
                ) : null;
              }}
            </Form.Item>

            <Form.Item
              name="filePattern"
              label="文件匹配模式"
              rules={[{ required: false }]}
            >
              <Input placeholder="例如: *.csv, *.json (可选)" />
            </Form.Item>
          </div>

          <div style={{ borderTop: '1px solid #f0f0f0', paddingTop: 20, marginTop: 20 }}>
            <h3 style={{ marginBottom: 20 }}>文件配置</h3>
            
            <Form.Item
              name="fileConfig"
              label="文件配置"
              rules={[{ required: true }]}
            >
              <Card title="文件配置">
                <Form.Item
                  name={['fileConfig', 'fileType']}
                  label="文件类型"
                  rules={[{ required: true, message: '请选择文件类型' }]}
                >
                  <Select placeholder="请选择文件类型">
                    <Option value="csv">CSV</Option>
                    <Option value="json">JSON</Option>
                    <Option value="xml">XML</Option>
                    <Option value="txt">文本文件</Option>
                  </Select>
                </Form.Item>
                
                <Form.Item
                  name={['fileConfig', 'encoding']}
                  label="文件编码"
                  initialValue="UTF-8"
                  rules={[{ required: true, message: '请选择文件编码' }]}
                >
                  <Select placeholder="请选择文件编码">
                    <Option value="UTF-8">UTF-8</Option>
                    <Option value="GBK">GBK</Option>
                    <Option value="ISO-8859-1">ISO-8859-1</Option>
                  </Select>
                </Form.Item>
                
                <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, currentValues) => {
                    return prevValues.fileConfig?.fileType !== currentValues.fileConfig?.fileType;
                  }}
                >
                  {({ getFieldValue }) => {
                    const fileType = getFieldValue(['fileConfig', 'fileType']);
                    return fileType === 'csv' ? (
                      <Form.Item
                        name={['fileConfig', 'delimiter']}
                        label="分隔符"
                        initialValue=","
                        rules={[{ required: true, message: '请输入分隔符' }]}
                      >
                        <Input placeholder="例如: , | ;" />
                      </Form.Item>
                    ) : null;
                  }}
                </Form.Item>
              </Card>
            </Form.Item>
          </div>

          <Form.Item>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <Button style={{ marginRight: 8 }} onClick={handleCancel}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                提交创建
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default DatasetCreate;